package cn.com.cifi.mars.web.action.sys;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.vo.price.FileUploadVO;
import cn.com.cifi.mars.bean.vo.sys.req.SaveOperGuideReqParam;
import cn.com.cifi.mars.bean.vo.sys.req.UpdateOperGuideReqParam;
import cn.com.cifi.mars.bean.vo.sys.rsp.OperGuideVo;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.constant.LogSrcEnum;
import cn.com.cifi.mars.entity.UploadFile;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.service.FileUploadService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.service.SysOperGuideService;
import cn.com.cifi.mars.util.FileUtils;
import cn.com.cifi.mars.util.WebUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 操作指引表 前端控制器
 * </p>
 *
 * @author yyd
 * @since 2019-11-18
 */
@Slf4j
@RestController
public class SysOperGuideController extends BaseAction implements ISysOperGuideController{

	@Autowired
	private SysOperGuideService sysOperGuideService;
	@Autowired
	private SysLogService sysLogService;
	@Autowired
	private FileUploadService fileUploadService;
	
	@Value("${file_directory}")
    private String file_directory;
    
    @Value("${approval_file_directory}")
    private String approval_file_directory;
    
    @Value("${pre_view_url}")
    private String pre_view_url;
    
    @Value("${download_url}")
    private String download_url;
	/**
	 * 上传文件
	 * @param apiVersion
	 * @param file
	 * @return
	 */
	@Override
    public R<FileUploadVO> fileUpload(String apiVersion, MultipartFile file) {
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		IdmUser user = getOperator();
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.ADD);
		bo.setSource(LogSrcEnum.PC);
		bo.setIp(WebUtils.getIpAddr(request));
		bo.setUrl(WebUtils.getUrl(request));
		bo.setModule("系统管理");
		bo.setTitle("上传操作指引");
		bo.setContent("上传操作指引");
		boolean msg = sysLogService.add(bo, user.getAlias());

    	if(file == null || file.isEmpty()) {
    		throw new MsgException(CodeEnum.FILE_IS_NULL);
    	}

        FileUploadVO uplpoadVO = new FileUploadVO();
        String account = user.getAlias();

        log.info("fileUpload->preViewUrl:"+pre_view_url);
        String fileName = file.getOriginalFilename();
        //获取后缀名
        String sname = fileName.substring(fileName.lastIndexOf("."));
        //文件扩展名
//        String extName = sname.substring(1).toLowerCase();
        //设置转换类型
//        String convertType = "3";
        //根据扩展名选择转换类型convertType
//        if (extName.equals("jpg") || extName.equals("png") || extName.equals("gif")){
//            convertType = "32";
//        }else if (extName.equals("zip") || extName.equals("rar")){
//            convertType = "19";
//        }else if (extName.equals("pdf")){
//            convertType = "34";
//        }else if (extName.equals("tif")){
//            convertType = "17";
//        }
        //截取文件名字(不带后缀)
        int i = fileName.lastIndexOf(".");
        String nameStr = fileName.substring(0, i);
        //时间格式化格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //获取当前时间并作为时间戳
        String timeStamp = simpleDateFormat.format(new Date());
        //拼接新的文件名
        String newFileName = nameStr+"_"+timeStamp+sname;
        List<UploadFile> uploadFile = fileUploadService.selectSameFileName(newFileName);
        if (uploadFile.size() > 0){
            throw new MsgException(CodeEnum.FILE_NAME_EXISTENT);
        }

        String newFilePath = null;
        String id = null;
        //上传文件
        try {
            newFilePath = file_directory + approval_file_directory + newFileName;
            InputStream ins = file.getInputStream();
            File toFile  = new File(newFilePath);
            FileUtils.inputStreamToFile(ins, toFile);
            ins.close();
            id = fileUploadService.saveFileUploadRecord(newFileName,sname,newFilePath,fileName,account);
        } catch (Exception e) {
            throw new MsgException(CodeEnum.FILE_UPLOAD_ERROR);
        }
        
//        CloseableHttpClient client = HttpClients.createDefault();
//        //在线预览转换
//        try {
//            HttpPost httpPost = new HttpPost(pre_view_url);
//            log.info("在线预览 pre_view_url= "+pre_view_url);
//            List<NameValuePair> param = new ArrayList<>();
//            param.add(new BasicNameValuePair("convertType",convertType));
//            param.add(new BasicNameValuePair("isDelSrc","1"));
//            param.add(new BasicNameValuePair("downloadUrl",download_url+id));
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param, "utf-8");
//            
//            log.info("在线预览 req: convertType="+convertType +" isDelSrc=1"+" downloadUrl="+download_url+id);
//            httpPost.setEntity(formEntity);
//            CloseableHttpResponse response = client.execute(httpPost);
//            try {
//                // 获取响应实体
//                HttpEntity entity = response.getEntity();
//                if (response.getStatusLine().getStatusCode() == 200){
//                    if (entity != null) {
//                        // 打印响应内容
//                        String content = EntityUtils.toString(entity);
//                        log.info("在线预览resp: "+content);
//                        JSONObject jsonObject = JSONObject.parseObject(content);
//                        JSONArray JsonData = jsonObject.getJSONArray("data");
//                        Integer result = jsonObject.getInteger("result");
//                        String message = jsonObject.getString("message");
//                        if (result == 0){
//                            if (null != JsonData && JsonData.size()>0){
//                                for (Object data : JsonData) {
//                                    String urlStr = data.toString();
//                                    //将预览地址更新到上传表
//                                    fileUploadService.updatePreViewUrl(id,urlStr);
//                                }
//                            }
//                        }else {
//                        	log.info("在线预览转换出错"+newFilePath+" response= "+response);
//                            uplpoadVO.setMessage(message);
//                        }
//                    }
//                }else {
//                	log.info("在线预览resp: "+response);
//                }
//            } finally {
//                response.close();
//            }
//        } catch (IOException e) {
//        	log.error("在线预览转换出错"+newFilePath);
//            log.error("###### errorMsg: ", e);
//        }finally {
//            try {
//                // 关闭连接,释放资源
//                client.close();
//            } catch (IOException e) {
//                log.error("###### errorMsg: ", e);
//            }
//        }
        UploadFile fileById = fileUploadService.selectFileById(id);
        uplpoadVO.setFilePath(newFilePath);
        uplpoadVO.setFileId(id);
        uplpoadVO.setFileName(fileName);
        uplpoadVO.setFileType(sname.substring(1));
        uplpoadVO.setPreviewUrl(fileById.getPreViewUrl());
        return ok(uplpoadVO);
    }


	
	
	/**
	  *  保存操作指引
	 */
	@Override
	public R<String> createOperGuide(String apiVersion, SaveOperGuideReqParam param) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		IdmUser user = getOperator();
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.ADD);
		bo.setSource(LogSrcEnum.PC);
		bo.setIp(WebUtils.getIpAddr(request));
		bo.setUrl(WebUtils.getUrl(request));
		bo.setModule("系统管理");
		bo.setTitle("保存操作指引");
		bo.setContent("保存操作指引");
		boolean msg = sysLogService.add(bo, user.getAlias());
		return ok(sysOperGuideService.insertOperGuide(param));
	}
	
	/**
	 * 查询操作指引
	 */
	@Override
	public R<OperGuideVo> getOperGuideList(String apiVersion,String current,String pageSize) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		IdmUser user = getOperator();
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.BROWSE);
		bo.setSource(LogSrcEnum.PC);
		bo.setIp(WebUtils.getIpAddr(request));
		bo.setUrl(WebUtils.getUrl(request));
		bo.setModule("系统管理");
		bo.setTitle("查询操作指引");
		bo.setContent("查询操作指引");
		boolean msg = sysLogService.add(bo, user.getAlias());
		return ok(sysOperGuideService.getOperGuideList(current,pageSize));
	}
	
	/**
	 * 删除操作指引
	 */
	@Override
	public R<String> deleteOperGuide(String apiVersion, String id) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		IdmUser user = getOperator();
		// 新增日志
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.DELETE);
		bo.setSource(LogSrcEnum.PC);
		bo.setIp(WebUtils.getIpAddr(request));
		bo.setUrl(WebUtils.getUrl(request));
		bo.setModule("系统管理");
		bo.setTitle("删除操作指引");
		bo.setContent("删除操作指引");
		boolean msg = sysLogService.add(bo, user.getAlias());
		return ok(sysOperGuideService.deleteOperGuide(id));
	}

	/**
	 * 编辑操作指引
	 */
	@Override
	public R<String> updateOperGuide(String apiVersion, UpdateOperGuideReqParam param) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		IdmUser user = getOperator();
		// 新增日志
		SysLogBO bo = new SysLogBO();
		bo.setEvent(LogEventEnum.EDIT);
		bo.setSource(LogSrcEnum.PC);
		bo.setIp(WebUtils.getIpAddr(request));
		bo.setUrl(WebUtils.getUrl(request));
		bo.setModule("系统管理");
		bo.setTitle("编辑操作指引");
		bo.setContent("编辑操作指引");
		boolean msg = sysLogService.add(bo, user.getAlias());
		return ok(sysOperGuideService.updateOperGuide(param));
	}
}
